package cn.chenc.framework.demo.service.impl;

import cn.chenc.framework.core.util.StringUtils;
import cn.chenc.framework.demo.dao.UserRepository;
import cn.chenc.framework.demo.entity.UserEntity;
import cn.chenc.framework.demo.service.UserService;
import cn.chenc.framework.jpa.service.BaseServiceImpl;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Predicate;
import jakarta.persistence.criteria.Root;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.ArrayList;
import java.util.List;

/**
 * 　@description: TODO
 * 　@author secret
 * 　@date 2021/5/14 15:47
 *
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<UserRepository,UserEntity, Integer> implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public List<UserEntity> queryAll() {
        return userRepository.findAll();
    }

    @Override
    public Page<UserEntity> queryUserPageList(UserEntity userEntity) {
        Pageable pageable = PageRequest.of(userEntity.getPageIndex()-1, userEntity.getPageSize());
        Specification<UserEntity> specification=new Specification<UserEntity>() {
            @Override
            public Predicate toPredicate(Root<UserEntity> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                if(StringUtils.isNotEmpty(userEntity.getUsername())){
                    Predicate predicate = criteriaBuilder.equal(root.get("username").as(String.class),userEntity.getUsername());
                    predicates.add(predicate);
                }
                Predicate[] pre = predicates.toArray(new Predicate[predicates.size()]);
                return criteriaQuery.where(pre).getRestriction();
            }
        };
        return userRepository.findAll(specification,pageable);
    }

    @Override
    @Transactional
    public void insertUser(UserEntity userEntity) {
        userRepository.save(userEntity);
    }

    @Override
    public Page<UserEntity> baseApiPage(UserEntity userEntity) throws Exception {
        Page <UserEntity> page = userRepository.getListByObject(userEntity,PageRequest.of(0,10));
        return page;
    }

}
